if '__main__' == __name__:

    import pandas as pd
    import os
    from PyCmpltrtok.common import sep
    import json
    from neo4j import GraphDatabase
    from python_nlp.kg.neo4j.config import NEO4J_CONFIG_AGR

    def _main():

        # 驱动
        driver = GraphDatabase.driver(**NEO4J_CONFIG_AGR)

        # 加索引和约束
        with driver.session() as ss:
            for query in [
                "CREATE CONSTRAINT IF NOT EXISTS FOR (n:Node) REQUIRE (n.name) IS UNIQUE",
                "CREATE INDEX IF NOT EXISTS FOR (p:Predicate) ON (p.name)",
            ]:
                print(query)
                ss.run(query)

        csv_dir = r'D:\_dell7590_root\sync\1_usb\M2\N5\x00700 农业知识图谱'

        csv_name_list = [
            'attributes.csv',
            'city_weather.csv',
            'weather_plant.csv',
            'wikidata_relation.csv',
            'wikidata_relation2.csv',
        ]

        with driver.session() as ss:

            for csv_name in csv_name_list:
                sep(csv_name)
                csv_path = os.path.join(csv_dir, csv_name)

                # 加载
                df = pd.read_csv(csv_path, delimiter=',', header=0)

                # https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas
                df = df.reset_index()
                for index, row in df.iterrows():
                    # 方便开发，限制条数
                    # if index > 4:
                    #     break
                    if index % 100 == 0:
                        print(csv_name, index)

                    # 拿出 SPO
                    n1 = row[df.columns[1]]
                    r = row[df.columns[2]]
                    n2 = row[df.columns[3]]
                    n1 = str(n1).strip()
                    r = str(r).strip()
                    n2 = str(n2).strip()

                    # 组合cypher
                    cypher = """\
                        MERGE (s:Node {name: %r})
                        MERGE (o:Node {name: %r})
                        MERGE (s)-[p:Predicate {name: %r}]->(o)
                        """ % (n1, n2, r)

                    # 入库
                    record = ss.run(cypher)
                    print('.', end='')
                print()

    _main()
